package com.syn.gmail.product.service.impl;

import com.syn.gmail.product.service.CategoryBrandRelationService;
import com.syn.gmail.product.vo.CatalogTwo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syn.common.utils.PageUtils;
import com.syn.common.utils.Query;

import com.syn.gmail.product.dao.CategoryDao;
import com.syn.gmail.product.entity.CategoryEntity;
import com.syn.gmail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

    @Override
    public List<CategoryEntity> getLevel1() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
    }

    /**
     * 查询二级分类封装成json
     * @return
     */
    @Override
    public Map<String, List<CatalogTwo>> getCataLog() {
        //所有一级分类
        List<CategoryEntity> level1 = getLevel1();
        //把list集合封装成map
        Map<String,List<CatalogTwo>> map = level1.stream().collect(Collectors.toMap(k->k.getCatId().toString(),v->{
            //1.每个一级分类查询到所有的二级分类
            List<CategoryEntity> categorys = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",v.getCatId()));
            List<CatalogTwo> categoryTwo = null;
            if(categorys != null){
                //遍历二级分类
                categoryTwo = categorys.stream().map(level2 ->{
                    //二级分类
                    CatalogTwo two = new CatalogTwo(v.getCatId().toString(),null,level2.getCatId().toString(),level2.getName());
                    //查找当前二级分类的三级分类
                    List<CategoryEntity> level3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",level2.getCatId()));
                    if(level3!=null){
                        //遍历三级分类
                        List<CatalogTwo.CatalogThree> l3 =  level3.stream().map(item->{
                            CatalogTwo.CatalogThree three = new CatalogTwo.CatalogThree(level2.getCatId().toString(),item.getCatId().toString(),item.getName());
                            return three;
                        }).collect(Collectors.toList());
                        two.setCatalog3List(l3);
                    }
                    return two;
                }).collect(Collectors.toList());
            }
            return categoryTwo;
        }));
        return map;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}